<?php
namespace app\api\controller\v1;

use app\api\model\User as Users;
use think\Request;
use Firebase\JWT\JWT;

class User extends Base
{

    public function getWxLogin(Users $user, Request $request)
    {

        $code = $request->param('code');
        $userInfo = $request->param('userInfo');

        $appid = config('wx.app_id');
        $secret = config('wx.app_secret');

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $output = curl_exec($ch);
        curl_close($ch);

        $output = json_decode($output,true);

        if (!isset($output['errcode'])){
            $userInfo = json_decode($userInfo,true);

            $session_key = $output['session_key'];
            $openid = $output['openid'];

            $user_id = $user->newUser($openid,$userInfo);
            $key = "session3rd";
            $data = [
                'user_id'=>$user_id,
                'sessionKey'=>$session_key,
                'openid'=>$openid
            ];

            $token = JWT::encode($data,$key,'HS256');

            return $this->success($token);

        }
        return $this->error();

    }


}
